package com.github.vortexdev.yachtclub.controllers;

import com.github.vortexdev.yachtclub.controllers.exceptions.WriteImageToResponseException;
import com.github.vortexdev.yachtclub.controllers.exceptions.YachtNotFoundException;
import com.github.vortexdev.yachtclub.models.Yacht;
import com.github.vortexdev.yachtclub.services.YachtService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;

/**
 * @author Sergey Parakhin (sergey.parahin@gmail.com)
 */
@Controller
public class YachtPhotoController {

    @Autowired
    YachtService yachtService;

    @RequestMapping(value = "/yacht/photo/{yachtId}", method = RequestMethod.GET)
    @ResponseBody
    public void yachtPhoto(@PathVariable int yachtId, HttpServletResponse response)
            throws YachtNotFoundException, WriteImageToResponseException {
        Yacht yacht = yachtService.getYacht(yachtId);

        if (yacht == null)
            throw new YachtNotFoundException("Yacht with id " + yachtId + " not found.");
        if (yacht.getPhoto() == null)
            throw new WriteImageToResponseException("Yacht has no photos");

        createResponse(yacht, yacht.getPhoto(), response);
    }

    private static void createResponse(Yacht yacht, byte[] data, HttpServletResponse response)
            throws WriteImageToResponseException {
        OutputStream op = null;
        try {
            op = response.getOutputStream();
            op.write(data);
            op.flush();
            response.setContentType(yacht.getContentType());
        } catch (IOException e) {
            throw new WriteImageToResponseException(e.getMessage());
        } finally {
            if (op != null)
                try {
                    op.close();
                } catch (IOException e) {
                    throw new WriteImageToResponseException(e.getMessage());
                }
        }
    }

}
